package com.tiger.admin.http.common.role;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiger.admin.Db;
import com.tiger.admin.SaveOperateLog;
import com.tiger.admin.http.common.role.dto.Page;
import com.tiger.admin.http.common.role.dto.Update;
import com.tiger.admin.dto.PaginationResult;
import com.tiger.admin.http.common.role.dto.Add;
import com.tiger.db.entity.Role;
import com.tiger.utils.ResponseUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.Objects;

@RestController
@RequestMapping("/role")
public class RoleController {
    private final Db db;

    public RoleController(Db db) {
        this.db = db;
    }


    @PostMapping("page")
    public Object page(@RequestBody Page page, @RequestAttribute("memberId") long memberId) {
        PaginationResult<Role> result = new PaginationResult<>();

        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("creator_id", memberId);


        if(page.getName() != null && !page.getName().isEmpty()) {
            wrapper.eq("name", page.getName());
        }

        long total = db.role.count(wrapper);
        if(total > 0) {
            result.setTotal(total);

            wrapper.orderByDesc("sort");
            wrapper.orderByDesc("id");


            result.setRows(db.role.pagination(wrapper, page.getPageNo(), page.getPageSize()));
        }


        return ResponseUtil.successRes(result);
    }

    @SaveOperateLog("新增角色")
    @PostMapping("add")
    public Object add(@RequestBody @Validated Add data, @RequestAttribute("memberId") long memberId) {


        if(db.role.exists(new QueryWrapper<Role>().eq("name", data.getName()).eq("creator_id", memberId))) {
            return ResponseUtil.failRes("已存在相同的名称");
        }

        Role row = new Role();


        BeanUtils.copyProperties(data, row);

        Instant now = Instant.now();


        row.setCreatorId(memberId);
        row.setCreateTime(now.getEpochSecond());



        boolean r = db.role.save(row);

        return r ? ResponseUtil.successRes(row) : ResponseUtil.failRes();

    }

    @SaveOperateLog("更新角色")
    @PostMapping("update/{id}")
    public Object add(@RequestBody @Validated Update data, @PathVariable Long id, @RequestAttribute("memberId") long memberId) {
        Role row = db.role.getById(id);
        if(row == null || row.getCreatorId() != memberId) return ResponseUtil.successRes();
        if(data.getName() != null && !Objects.equals(data.getName(), row.getName())) {
            if(db.role.exists(new QueryWrapper<Role>().eq("name", data.getName()).eq("creator_id", memberId))) {
                return ResponseUtil.failRes("已存在相同的名称");
            }
        }


        Instant now = Instant.now();

        BeanUtils.copyProperties(data, row);


        row.setId(id);
        row.setUpdateTime(now.getEpochSecond());


        boolean r = db.role.updateById(row);

        return r ? ResponseUtil.successRes(row) : ResponseUtil.failRes();

    }

    @SaveOperateLog("删除角色")
    @PostMapping("delete/{id}")
    public Object del(@PathVariable long id, @RequestAttribute("memberId") long memberId) {
        Role row = db.role.getOne(new QueryWrapper<Role>().select("id", "creator_id").eq("id", id));
        if(row == null || row.getCreatorId() != memberId) return ResponseUtil.successRes();
        boolean r = db.role.removeById(id);
        return r ? ResponseUtil.successRes() : ResponseUtil.failRes();
    }

    //获取用户创建的角色
    @GetMapping("list")
    public Object list(@RequestAttribute("memberId") long memberId) {
        return ResponseUtil.successRes(db.role.list(new QueryWrapper<Role>().select("id", "name").eq("creator_id", memberId)));
    }
}
